import Vue from "vue";
import VueRouter from "vue-router";

const originalPush = VueRouter.prototype.push;
window.routerHistory; // 记录路由历史

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(console.warn);
};

VueRouter.prototype.replace = function push(location) {
  return originalPush.call(this, location).catch(console.warn);
};

Vue.use(VueRouter);

const defaultTitle = "三国志战略版图鉴 - Ganke游戏社区";

const routes = [
  {
    path: "/",
    redirect: { name: "heroes", keep: true, pid: 0 },
    component: () => import("../pages/home/"),
  },
  {
    path: "/heroes",
    name: "heroes",
    meta: { title: "武将", keep: true, pid: 0 },
    component: () => import("../pages/home/"),
  },
  {
    path: "/tactics",
    name: "tactics",
    meta: { title: "战法", keep: true, pid: 0 },
    component: () => import("../pages/home/"),
  },
  {
    path: "/books",
    name: "books",
    meta: { title: "兵书", keep: true, pid: 0 },
    component: () => import("../pages/home/"),
  },
  // 武将详情
  {
    path: "/heroe/:id",
    name: "HeroeDetails",
    meta: { title: "武将", keep: true, pid: 0 },
    component: () => import("../pages/heroe/"),
  },
  // 战法详情
  {
    path: "/tactic/:id",
    name: "TacticDetails",
    meta: { title: "战法", keep: true, pid: 0 },
    component: () => import("../pages/tactic/"),
  },
  // 配将页面首页
  {
    path: "/match",
    name: "FormsMatch",
    meta: { title: "配将助手", keep: true, pid: 1 },
    component: () => import("../pages/match/index/"),
  },
  {
    path: "/match/:name",
    name: "FormsMatchName",
    meta: { title: "配将助手", keep: true, pid: 1 },
    component: () => import("../pages/match/index/"),
  },
  // 我的武将
  {
    path: "/myheroe",
    name: "MyHeroe",
    meta: { title: "我的武将", pid: 1 },
    component: () => import("../pages/myheroe/"),
  },
  // 招募武将
  {
    path: "/enlist",
    name: "Enlist",
    meta: { title: "招募武将", clear: true, pid: 1 },
    component: () => import("../pages/enlist/"),
  },
  // 发布阵容
  {
    path: "/publish",
    name: "Publish",
    meta: { title: "发布阵容", pid: 1 },
    component: () => import("../pages/publish/"),
  },
  // 阵容编辑
  {
    path: "/forms/edit/:id",
    name: "FormsEdit",
    meta: { title: "阵容编辑", pid: 1 },
    component: () => import("../pages/publish/"),
  },
  // 阵容详情
  {
    path: "/forms/:id",
    name: "FormsDetails",
    meta: { title: "阵容分享", pid: 1 },
    component: () => import("../pages/forms/"),
  },
  {
    path: "/loading",
    name: "Loading",
    meta: { title: "加载中", pid: -1 },
    component: () => import("../pages/loading/"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: "/tool1",
  routes,
});

// 拦截器
router.beforeEach((to, from, next) => {
  if (!window.routerHistory) {
    window.routerHistory = [
      {
        path: to.path,
        scrollTop: 0,
      },
    ];
  }

  if (to.meta.title) {
    document.title = to.meta.title + " - " + defaultTitle;
  } else document.title = defaultTitle;

  next();
});

router.afterEach((to) => {
  if (window.from || window.token) {
    let arr = [];
    if (window.from) arr.push(`from=${window.from}`);
    if (window.token) arr.push(`token=${window.token}`);
    Object.keys(to.query).forEach((item) => {
      if (item !== "from" && item !== "token") {
        arr.push(`${item}=${to.query[item]}`);
      }
    });
    const newUrl = location.pathname + `?${arr.join("&")}`;
    window.history.replaceState("", "", newUrl);
  }

  // 发送通用链接埋点
  setTimeout(() => {
    // 跳过loading页面
    if (to.name === "Loading") return;
    try {
      window.gankeTool.collectEvent("predefinePageView", {
        url: window.gankeTool.funcUrlDel([
          "token",
          "t_source",
          "page_title",
          "pkg_name",
          "origin",
        ]),
        url_path: window.location.pathname,
      });
    } catch (e) {
      console.error("通用链接埋点异常", e);
    }
  }, 0);

  setTimeout(() => {
    let _router = window.routerHistory[window.routerHistory.length - 1];
    if (_router.scrollTop > 0 && Vue.prototype.scroll) {
      Vue.prototype.scroll.scrollTo({ y: _router.scrollTop * 100 + "%" }, 0);
    }
  }, 0);
});

router.back = function () {
  window.routerback = true;
  if (window.routerHistory.length > 1) {
    window.routerHistory.pop();
    history.go(-1);
  } else {
    console.log(33333);
    let last_pages = ["/heroes", "/match"];
    if (
      window.routerHistory[0] &&
      last_pages.indexOf(window.routerHistory[0].path) !== -1
    ) {
      if (window.from == "ios" || window.from == "android") {
        console.log(55555);
        console.log(window.injectedAll);
        window.injectedAll.finishWebView();
      } else if (window.from == "vivo") {
        console.log(66666);
        window.location.replace(window.vivoURL);
      } else {
        console.log(77777);
        console.log("无法返回");
      }
    } else {
      console.log(44444);
      window.routerHistory = [];
      if (this.currentRoute.name === "FormsDetails") {
        this.push("/match");
      } else {
        this.push("/heroes");
      }
      //
    }
  }
};

const _push = router.push;
router.push = function (location) {
  // console.log("正常跳转");
  let scroll = { v: 0, h: 0 };
  if (Vue.prototype.scroll) {
    scroll = Vue.prototype.scroll.getScrollProcess();
  }
  if (window.routerHistory[window.routerHistory.length - 1]) {
    window.routerHistory[window.routerHistory.length - 1].scrollTop = scroll.v;
  }
  if (typeof location === "string") {
    window.routerHistory.push({ path: location, scrollTop: 0 });
  } else {
    window.routerHistory.push({ path: location.path, scrollTop: 0 });
  }
  _push.call(this, location);
};

const _replace = router.replace;
router.replace = function (location) {
  // console.log("清除堆栈跳转");
  window.routerHistory = [];
  if (typeof location === "string") {
    window.routerHistory.push({ path: location, scrollTop: 0 });
  } else {
    window.routerHistory.push({ path: location, scrollTop: 0 });
  }
  _replace.call(this, location);
};

Vue.prototype.jumpPage = (location) => {
  router.push(location);
};

window.addEventListener("popstate", function () {
  let path = window.location.pathname.replace(router.options.base, "");
  if (!window.routerback) {
    let oldPath = window.routerHistory[window.routerHistory.length - 2];
    if (oldPath.path === path) {
      window.routerback = true;
      window.routerHistory.pop();
    } else {
      let scroll = Vue.prototype.scroll.getScrollProcess();
      if (window.routerHistory[window.routerHistory.length - 1]) {
        window.routerHistory[window.routerHistory.length - 1].scrollTop =
          scroll.v;
      }
      window.routerHistory.push({ path });
    }
  }
});

export default router;
